﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FlaUI.Core.AutomationElements;
using FlaUI.Core.Definitions;
using FlaUI.UIA3;
using QQTools.Data.Enums.ForwardGroupMessage;
using QQTools.Logging;
using QQTools.Utils;
using static QQTools.Utils.Utils;

namespace QQTools.Services.Automation
{
    public class ForwardGroupMsgAuto
    {
        /// <summary>
        /// QQ进程 ID
        /// </summary>
        protected int _pid;
        /// <summary>
        /// QQ主窗口句柄
        /// </summary>
        protected IntPtr _qqMainWindowHandle;

        public ForwardGroupMsgAuto(int pid)
        {
            _pid = pid;
            // 获取 QQ 主窗口句柄
            _qqMainWindowHandle = Win32Api.GetWindowHandle(pid, "QQ", "TXGuiFoundation", false);
        }


        public async void ForwardGroupMsg()
        {

            await Task.Delay(1000);

        }


        public async Task<(ForwardGroupMsgResult Result, int Index)> ForwardGroupMsg(string number, string msgType, CancellationToken token, int attempt = 1)
        {
            // 当前发送资源的索引
            int index = 0;
            try
            {
                // 先清理窗口, 避免影任务
                InitCleanWindow();

                // 1. 打开 我的收藏窗口
                AutomationElement collectionWindow = await OpenMyCollectionWindow(token);
                if (collectionWindow == null)
                {
                    return (ForwardGroupMsgResult.OpenWindowFailed, index); // 重试
                }
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[转发] 任务已取消2221");
                    return (ForwardGroupMsgResult.TaskCancelled, index);
                }

                // 2. 点击我的收藏窗口的选项卡
                await Task.Delay(1000);
                if (!await ClickMyCollectionTab(collectionWindow, msgType))
                {
                    FlauiAuto.CloseWindow(collectionWindow);
                    return (ForwardGroupMsgResult.ErrorWindow, index); // 重试
                }
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[转发] 任务已取消2222");
                    return (ForwardGroupMsgResult.TaskCancelled, index);
                }

                // 3. 比如发送索引1的图片
                //if (!await InputMyCollectionSearch(collectionWindow, index.ToString()))
                //{
                //    FlauiAuto.CloseWindow(collectionWindow);
                //    return ForwardGroupMsgResult.OpenWindowFailed; // 重试
                //}
                //if (token.IsCancellationRequested)
                //{
                //    LogManager.Info("[转发] 任务已取消2223");
                //    return ForwardGroupMsgResult.TaskCancelled;
                //}
                // 3. 随机选择一个当前分类的资源
                var (selectResult, forwardIndex) = await SelectMsgItem(collectionWindow, msgType);
                index = forwardIndex;
                // 3. 随机选择一个当前分类的资源
                if (!selectResult)
                {
                    FlauiAuto.CloseWindow(collectionWindow);
                    return (ForwardGroupMsgResult.ResourceNotFound, index); // 重试
                }

                await Task.Delay(1000);

                // 4. 打开 转发窗口
                if (!await OpenForwardWindow(collectionWindow))
                {
                    FlauiAuto.CloseWindow(collectionWindow);
                    return (ForwardGroupMsgResult.ResourceNotFound, index); // 重试
                }
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[转发] 任务已取消2223");
                    return (ForwardGroupMsgResult.TaskCancelled, index);
                }
                // 5. 获取 转发窗口
                await Task.Delay(1000);
                AutomationElement forwardWindow = GetForwardWindow(collectionWindow);
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[转发] 任务已取消2224");
                    return (ForwardGroupMsgResult.TaskCancelled, index);
                }
                // 6. 输入 转发目标
                await Task.Delay(1000);
                ForwardGroupMsgResult inputResult = await InputForwardTarget(forwardWindow, number);
                if (inputResult != ForwardGroupMsgResult.Success)
                {
                    FlauiAuto.CloseWindow(forwardWindow);
                    return (inputResult, index); // 重试
                }
                if (token.IsCancellationRequested)
                {
                    LogManager.Info("[转发] 任务已取消2225");
                    return (ForwardGroupMsgResult.TaskCancelled, index);
                }
                //// 7. 等待转发结果
                //await Task.Delay(1000);
                //if (!GetForwardResult(forwardWindow))
                //{
                //    await Task.Delay(1000);
                //    continue; // 重试
                //}
                await Task.Delay(1000);
                // 8. 任务成功，关闭窗口并返回 true
                FlauiAuto.CloseWindow(forwardWindow);
                LogManager.Info($"[ForwardGroupMsg] 第 {attempt} 次: 成功, 目标:{number}, 类型:{msgType}, 索引:{index}");
                return (ForwardGroupMsgResult.Success, index);
            }
            catch (Exception ex)
            {
                LogManager.Info($"[ForwardGroupMsg] 第 {attempt} 次尝试失败: {ex.Message}", ex);
            }
            return (ForwardGroupMsgResult.Unknown, index); // 任务失败
        }


        /// <summary>
        /// 转发群消息
        /// </summary>
        /// <param name="number">号码</param>
        /// <param name="msgType">消息类名</param>
        /// <param name="index">下标</param>
        /// <returns></returns>
        public async Task ForwardGroupMsgWithRetry(string number, string msgType, int index, CancellationToken token)
        {
            // 先清理窗口, 避免影任务
            InitCleanWindow();
            int maxRetries = 3; // 最大重试次数
            int retryCount = 0; // 当前重试次数

            while (retryCount < maxRetries)
            {
                try
                {
                    Console.WriteLine($"开始尝试第 {retryCount + 1} 次...");

                    // 1. 打开 我的收藏窗口
                    AutomationElement collectionWindow = await OpenMyCollectionWindow(token);
                    if (collectionWindow == null)
                    {
                        throw new Exception("无法打开我的收藏窗口");
                    }

                    // 2. 点击我的收藏窗口的选项卡
                    await Task.Delay(1000);
                    if (await ClickMyCollectionTab(collectionWindow, msgType) == false)
                    {
                        throw new Exception("无法点击我的收藏窗口的选项卡");
                    }

                    // 3. 比如发送 索引1的图片
                    if (await InputMyCollectionSearch(collectionWindow, index.ToString()) == false)
                    {
                        throw new Exception($"无法输入索引:{index}的{msgType}");
                    }

                    // 4. 打开 转发窗口
                    await Task.Delay(1000);
                    if (await OpenForwardWindow(collectionWindow) == false)
                    {
                        throw new Exception("无法打开转发窗口");
                    }

                    // 5. 获取 转发窗口
                    await Task.Delay(1000);
                    AutomationElement forwardWindow = GetForwardWindow(collectionWindow);
                    if (forwardWindow == null)
                    {
                        throw new Exception("无法获取转发窗口");
                    }

                    // 6. 输入 转发目标
                    await Task.Delay(1000);

                    ForwardGroupMsgResult inputResult = await InputForwardTarget(forwardWindow, number);
                    if (inputResult != ForwardGroupMsgResult.Success)
                    {
                        throw new Exception("无法输入转发目标");

                    }
                    // 7. 点击 转发按钮
                    //await Task.Delay(1000);
                    //if (await ClickForwardButton(forwardWindow) == false)
                    //{
                    //    throw new Exception("无法点击转发按钮");
                    //}

                    // 8. 等待转发结果
                    await Task.Delay(1000);
                    if (GetForwardResult(forwardWindow) == false)
                    {
                        throw new Exception("转发失败");
                    }

                    // 如果所有步骤都成功，退出循环
                    LogManager.Info("[ForwardGroupMsgWithRetry] 转发任务成功完成！");
                    // 8.1关闭转发窗口
                    FlauiAuto.CloseWindow(forwardWindow);
                    break;
                }
                catch (Exception ex)
                {
                    // 清理窗口, 避免影任务
                    InitCleanWindow();
                    retryCount++;
                    LogManager.Info($"第 {retryCount} 次尝试失败: {ex.Message}");

                    // 如果达到最大重试次数，抛出异常
                    if (retryCount >= maxRetries)
                    {
                        LogManager.Warn("已达到最大重试次数，任务失败！");
                        throw;
                    }

                    // 等待一段时间后重试
                    await Task.Delay(2000); // 可根据需要调整等待时间
                }
            }
        }

        /// <summary>
        /// 初始化干净的窗口
        /// </summary>
        /// <returns></returns>
        public void InitCleanWindow()
        {
            LogManager.Info($"[InitCleanWindow] 开始初始化干净的窗口");
            try
            {

                Win32Api.CloseAllWindows("TXGuiFoundation", "安全提醒");
                // 关闭 转发窗口
                //Win32Api.CloseAllWindows("TXGuiFoundation", "转发");
                // 群公告窗口
                //Win32Api.CloseAllWindows("TXGuiFoundation", "");
                // 关闭 我的收藏窗口
                //Win32Api.CloseAllWindowsEndsWith("TXGuiFoundation", "的 收藏");
                //Win32Api.CloseAllWindowsEndsWith("TXGuiFoundation", "个会话");
                LogManager.Info($"[InitCleanWindow] 完成初始化干净的窗口");
            }
            catch (Exception ex)
            {
                LogManager.Error($"[InitCleanWindow] 初始化干净的窗口发生错误: {ex.Message}");
            }
        }



        /// <summary>
        /// 打开我的收藏窗口
        /// </summary>
        /// <returns></returns>
        public async Task<AutomationElement> OpenMyCollectionWindow(CancellationToken token)
        {
            if (token.IsCancellationRequested)
            {
                LogManager.Info("[转发] 任务已取消11137");
                return null;
            }
            LogManager.Info($"[OpenMyCollectionWindow] 准备打开->我的收藏窗口");
            if (_qqMainWindowHandle == IntPtr.Zero)
            {
                LogManager.Error("[OpenMyCollectionWindow] 主窗口句柄无效");
                return null;
            }

            try
            {
                using (var automation = new UIA3Automation())
                {
                    // 隐藏其他QQ窗口
                    Win32Api.HideAllWindowsExcept("QQ", "TXGuiFoundation", _qqMainWindowHandle);
                    // 强制显示QQ主窗口
                    Win32Api.SetTopWindow(_qqMainWindowHandle);
                    await Task.Delay(1500);
                    // 移动窗口到屏幕右上角, 不能靠近边缘,否则QQ会自动收起来
                    Win32Api.MoveWindowsToPosition(_qqMainWindowHandle, (int)(Screen.PrimaryScreen.Bounds.Width * 0.85), 100);
                    AutomationElement mainWindow = automation.FromHandle(_qqMainWindowHandle);
                    if (token.IsCancellationRequested)
                    {
                        LogManager.Info("[转发] 任务已取消11138");
                        return null;
                    }
                    if (mainWindow == null)
                    {
                        LogManager.Error("[OpenMyCollectionWindow] 主窗口句柄无效");
                        return null;
                    }
                    await Task.Delay(1500);
                    if (token.IsCancellationRequested)
                    {
                        LogManager.Info("[转发] 任务已取消11139");
                        return null;
                    }
                    // 1. 点击主菜单按钮
                    if (!await ClickQQMainMenuBtn(mainWindow))
                    {
                        LogManager.Error("[OpenMyCollectionWindow] 点击主菜单按钮失败");
                        return null;
                    }
                    await Task.Delay(1500);
                    if (token.IsCancellationRequested)
                    {
                        LogManager.Info("[转发] 任务已取消11140");
                        return null;
                    }

                    // 2. 点击我的收藏
                    if (!await ClickQQMainMenuItem(mainWindow, "我的收藏"))
                    {
                        LogManager.Error("[OpenMyCollectionWindow] 点击“我的收藏”菜单项失败");
                        return null;
                    }
                    await Task.Delay(1500);
                    if (token.IsCancellationRequested)
                    {
                        LogManager.Info("[转发] 任务已取消11141");
                        return null;
                    }
                    // 3. 点击我的收藏打开我的收藏窗口
                    AutomationElement collectionWindow = GetMyCollectionWindow();
                    if (collectionWindow == null)
                    {
                        LogManager.Error("[OpenMyCollectionWindow] 获取“我的收藏”窗口失败");
                        return null;
                    }
                    LogManager.Info($"[OpenMyCollectionWindow] 打开成功->我的收藏窗口");
                    // 移动收藏窗口到屏幕右上角
                    Win32Api.MoveWindowsToPosition(collectionWindow.Properties.NativeWindowHandle, (int)(Screen.PrimaryScreen.Bounds.Width * 0.18), 0);
                    return collectionWindow;
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[OpenMyCollectionWindow] 发生异常: {ex.Message}", ex);
                return null;
            }
        }


        /// <summary>
        /// 点击 QQ 主菜单按钮
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <returns></returns>
        public async Task<bool> ClickQQMainMenuBtn(AutomationElement mainWindow)
        {
            LogManager.Info($"[ClickQQMainMenuBtn] 准备点击-> QQ主菜单按钮");
            if (mainWindow != null)
            {
                // 获取所有按钮，找到 LegacyIAccessible.Description = “主菜单” 的按钮
                var buttons = mainWindow.FindAllDescendants(cf =>
                    cf.ByControlType(ControlType.Button)
                );

                foreach (var button in buttons)
                {
                    try
                    {
                        // 尝试使用 LegacyIAccessiblePattern 获取描述信息
                        var legacyPattern = button.Patterns.LegacyIAccessible.PatternOrDefault;
                        if (legacyPattern != null)
                        {
                            var description = legacyPattern.Description;
                            // Console.WriteLine($"Description: {description}");

                            if (string.Equals("主菜单", description))
                            {
                                // 让窗口置顶
                                mainWindow.SetForeground();
                                await Task.Delay(1000);
                                // 点击主菜单按钮
                                button.Click();
                                await Task.Delay(1000);
                                LogManager.Info("[GetQQMainMenuBtn] 点击成功->主菜单按钮");
                                return true;
                            }
                        }
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        LogManager.Error($"[GetQQMainMenuBtn] 点击QQ主菜单按钮失败, 原因:拒绝访问。请确保程序具有足够的权限。", ex);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[GetQQMainMenuBtn] 点击QQ主菜单按钮失败, 原因:{ex.Message}", ex);
                    }
                }
            }
            LogManager.Error("[GetQQMainMenuBtn] 没找到QQ主菜单按钮");
            return false;
        }





        /// <summary>
        /// 点击 QQ 主菜单中的菜单项
        /// </summary>
        /// <param name="mainWindow">QQ主窗口</param>
        /// <param name="itemName">要点击的菜单项</param>
        /// <returns></returns>
        public async Task<bool> ClickQQMainMenuItem(AutomationElement mainWindow, string itemName)
        {
            LogManager.Info($"[ClickQQMainMenuItem] 开始点击->QQ主菜单：{itemName}");
            // 判断 mainWindow 是否为空
            if (mainWindow == null)
            {
                LogManager.Error("[ClickQQMainMenuItem] mainWindow 为空");
                return false;
            }

            try
            {
                AutomationElement menuWindow = mainWindow.FindFirstChild(cf =>
                        cf.ByControlType(ControlType.Menu)
                    //.And(cf.ByName("TXMenuWindow"))
                    //.And(cf.ByClassName("TXGuiFoundation"))
                    );
                if (menuWindow != null)
                {
                    // 找到 ControlType:MenuItem Name: itemName 的元素
                    // 自定义搜索逻辑
                    var allMenuItems = menuWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.MenuItem));
                    foreach (var menuItem in allMenuItems)
                    {
                        if (string.Equals(menuItem.Name, itemName, StringComparison.OrdinalIgnoreCase))
                        {
                            // 让窗口置顶
                            mainWindow.SetForeground();
                            await Task.Delay(1000);
                            menuItem.Click();
                            await Task.Delay(1000);
                            LogManager.Info($"[ClickQQMainMenuItem] 点击成功QQ主菜单项：{itemName}");
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[ClickQQMainMenuItem] 点击失败->QQ主菜单项：{itemName}， 原因：", ex);
            }
            LogManager.Error($"[ClickQQMainMenuItem] 点击失败->QQ主菜单项：{itemName}");
            return false;
        }


        /// <summary>
        /// 获取 我的收藏 窗口
        /// </summary>
        /// <returns></returns>
        public AutomationElement GetMyCollectionWindow()
        {
            LogManager.Info($"[GetMyCollectionWindow] 准备获取->我的收藏窗口");
            try
            {
                using (var automation = new UIA3Automation())
                {
                    // 确保 _pid 有效
                    if (_pid <= 0)
                    {
                        LogManager.Error("[GetMyCollectionWindow] 无效的进程 ID！");
                        return null;
                    }

                    // 异步查找窗口并处理超时
                    AutomationElement window = null;
                    for (int i = 0; i < 10; i++)
                    {
                        List<(IntPtr Handle, string Title)> list = Win32Api.FindWindowsByTitleSuffixAndProcessId("的 收藏", _pid);
                        if (list.Count > 0)
                        {
                            window = automation.FromHandle(list[0].Handle);
                            break;
                        }
                    }

                    if (window != null)
                    {
                        LogManager.Info($"[GetMyCollectionWindow] 获取成功->我的收藏窗口：{window.Name}");
                        return window;
                    }
                    else
                    {
                        LogManager.Error("[GetMyCollectionWindow] 获取超时->我的收藏窗口！");
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并记录日志
                LogManager.Error($"[GetMyCollectionWindow] 获取时发生异常：{ex.Message}");
            }

            return null;
        }


        /// <summary>
        /// 点击 我的收藏 窗口的 类型标签
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <param name="tabName"></param>
        public async Task<bool> ClickMyCollectionTab(AutomationElement mainWindow, string tabName)
        {
            LogManager.Info($"[ClickMyCollectionTab] 准备成功->收藏窗口分类：{tabName}");
            if (mainWindow == null)
            {
                LogManager.Error("[ClickMyCollectionTab] mainWindow 为空！");
                return true;
            }

            try
            {
                AutomationElement tabItem = mainWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.TabItem).And(cf.ByName(tabName)));
                if (tabItem != null)
                {
                    await Task.Delay(1000);
                    tabItem.Click();
                    LogManager.Info($"[ClickMyCollectionTab] 点击成功->收藏窗口分类：{tabName}");
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[ClickMyCollectionTab] 发生异常：{ex.Message}");
            }
            LogManager.Error($"[ClickMyCollectionTab] 点击失败->收藏窗口分类：{tabName}");
            return false;
        }


        /// <summary>
        /// 输入 我的收藏 窗口的 搜索框
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <param name="index">发送内容的索引</param>
        /// <returns></returns>
        public async Task<bool> InputMyCollectionSearch(AutomationElement mainWindow, string index)
        {
            if (mainWindow == null)
            {
                LogManager.Error("[InputMyCollectionSearch] mainWindow 为空！");
                return false;
            }

            try
            {
                AutomationElement searchEdit = mainWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.Edit)).FirstOrDefault();
                if (searchEdit == null)
                {
                    LogManager.Error($"[ClickMyCollectionTab] 没找到输入框");
                    return false;
                }
                searchEdit.Click();
                await Task.Delay(1000);

                // 根据 下标(做到图片顺序发送) 清除并输入
                FlauiAuto.ClearAndSendKeys(searchEdit, index);
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Error($"[ClickMyCollectionTab] 发生异常：{ex.Message}");
            }
            return false;

        }

        /// <summary>
        /// 点击 转发按钮 打开转发窗口
        /// </summary>
        public async Task<bool> OpenForwardWindow(AutomationElement mainWindow)
        {
            if (mainWindow == null)
            {
                LogManager.Error("[ClickMyCollectionForwardBtn] mainWindow 为空！");
                return false;
            }
            try
            {
                AutomationElement[] btns = mainWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.Button));
                if (btns.Length < 5)
                {
                    return false;
                }

                // 最终手段，直接点击倒数第二个按钮
                if (btns.Length == 7)
                {
                    btns[2].Click();
                    await Task.Delay(1000);
                    return true;
                }

                for (int i = 0; i < btns.Length; i++)
                {
                    AutomationElement btn = btns[i];
                    LogManager.Info($"[ClickMyCollectionForwardBtn] 寻找转发按钮, btn.Name:{btn.Name}");

                    var forwardBtnRect = btn.Properties.BoundingRectangle.Value;

                    if (forwardBtnRect.IsEmpty)
                    {
                        continue;
                    }

                    if (forwardBtnRect.Width < 30 && forwardBtnRect.Height < 25)
                    {

                        var mainRect = mainWindow.Properties.BoundingRectangle.Value;
                        if (mainRect.IsEmpty)
                        {
                            continue;
                        }
                        if (forwardBtnRect.Left > mainRect.Right - 100 && forwardBtnRect.Right < mainRect.Right - 50) // 如果在右侧 100像素内，则认为是转发按钮
                        {
                            await Task.Delay(1000);
                            btn.Click();
                            await Task.Delay(1000);
                            return true;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[ClickMyCollectionForwardBtn] 寻找转发按钮, 发生异常：{ex.Message}");
            }
            return false;
        }


        /// <summary>
        /// 获取 转发窗口 AutomationElement
        /// </summary>
        public static AutomationElement GetForwardWindow(AutomationElement mainWindow)
        {
            try
            {
                AutomationElement forwardWindow = mainWindow.FindFirstDescendant(cf =>
                    cf.ByControlType(ControlType.Window)
                    .And(cf.ByName("转发")));

                if (forwardWindow != null)
                {
                    LogManager.Info("[GetForwardWindow] 找到转发窗口");
                    return forwardWindow;
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[GetForwardWindow] 寻找 转发窗口 发生异常: {ex.Message}", ex);
            }
            return null;
        }


        /// <summary>
        /// 输入 转发目标
        /// </summary>
        public async Task<ForwardGroupMsgResult> InputForwardTarget(AutomationElement forwardWindow, string groupNumber)
        {
            if (forwardWindow == null)
            {
                LogManager.Error("[InputForwardTarget] forwardWindow 为空！");
                return ForwardGroupMsgResult.OpenWindowFailed;
            }

            try
            {
                // 窗口置顶
                Win32Api.SetTopWindow(forwardWindow.Properties.NativeWindowHandle);

                // 输入待转发群号
                AutomationElement searchEdit = forwardWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.Edit)
                .And(cf.ByName("输入查找关键字"))).FirstOrDefault();
                if (searchEdit == null)
                {
                    LogManager.Error($"[InputForwardTarget] 没找到输入框");
                    return ForwardGroupMsgResult.ErrorWindow;
                }
                await Task.Delay(1000);
                // 清除并输入
                FlauiAuto.ClearAndSendKeys(searchEdit, groupNumber);
                await Task.Delay(1000);

                // 动态等待搜索结果并勾选
                bool selected = false;
                for (int i = 0; i < 10; i++)
                {
                    selected = SelectForwardTarget(forwardWindow, groupNumber);
                    if (selected)
                    {
                        break;
                    }
                    await Task.Delay(1000);
                }

                if (selected == false)
                {
                    LogManager.Error($"[InputForwardTarget] 没找到被转发的:{groupNumber}");
                    return ForwardGroupMsgResult.GroupNotFound;
                }
                await Task.Delay(1500);
                // 获取 转发窗口 的 转发按钮
                AutomationElement forwardBtn = forwardWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Button)
                .And(cf.ByName("转发")));
                if (forwardBtn == null)
                {
                    LogManager.Error($"[InputForwardTarget] 没找到 转发窗口 的 转发按钮");
                    return ForwardGroupMsgResult.ErrorWindow;
                }
                if (forwardBtn.IsEnabled == false)
                {
                    LogManager.Error($"[InputForwardTarget] 转发窗口 的 转发按钮不可用");
                    return ForwardGroupMsgResult.ErrorWindow;
                }
                await Task.Delay(1000);
                forwardBtn.Click();
                await Task.Delay(1000);
                return ForwardGroupMsgResult.Success;

            }
            catch (Exception ex)
            {
                LogManager.Error($"[InputForwardTarget] 发生异常：{ex.Message}");
            }
            return ForwardGroupMsgResult.Unknown;
        }


        /// <summary>
        /// 勾选转发搜索的结果   
        /// </summary>
        /// <param name="forwardWindow"></param>
        /// <param name="groupNumber"></param>
        /// <returns></returns>
        private static bool SelectForwardTarget(AutomationElement forwardWindow, string groupNumber)
        {
            if (forwardWindow == null)
            {
                LogManager.Error("[SelectForwardTarget] forwardWindow 为空!");
                return false;
            }

            // 预先计算匹配字符串
            string search1 = $"({groupNumber})";
            string search2 = $"{groupNumber}@";
            try
            {
                AutomationElement[] selectItems = forwardWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.ListItem));
                foreach (AutomationElement item in selectItems)
                {
                    if (item == null) continue;

                    // 检查Name属性是否存在且有效
                    if (!item.Properties.Name.IsSupported) continue;

                    string name = item.Name;
                    if (string.IsNullOrEmpty(name)) continue;

                    if (name.Contains(search1) || name.Contains(search2))
                    {
                        item.Click();
                        LogManager.Info($"[SelectForwardTarget] 勾选被转发目标: {name}");
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Error($"[SelectForwardTarget] 选择被转发目标失败: {ex.Message}", ex);
            }
            LogManager.Info($"[SelectForwardTarget] 没找到被转发目标: {groupNumber}");
            return false;
        }


        /// <summary>
        /// 获取转发结果
        /// </summary>
        /// <param name="forwardWindow"></param>
        /// <returns></returns>
        private bool GetForwardResult(AutomationElement forwardWindow)
        {
            if (forwardWindow == null)
            {
                LogManager.Error("[GetForwardResult] forwardWindow 为空!");
                return false;
            }
            // 1.转发成功
            AutomationElement resultElement = forwardWindow.FindFirstDescendant(cf => cf.ByControlType(ControlType.Text).And(cf.ByName("转发成功")));
            if (resultElement != null)
            {
                LogManager.Info($"[GetForwardResult] 转发成功");
                return true;
            }
            // 2.转发失败
            return false;
        }


        /// <summary>
        /// 随机选择分类的项
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <param name="msgType"></param>
        /// <returns></returns>
        public async Task<(bool selectResult, int forwardIndex)> SelectMsgItem1(AutomationElement mainWindow, string msgType)
        {
            int forwardIndex = 0;
            if (mainWindow == null)
            {
                LogManager.Error("[SelectMsgItem] mainWindow 为空！");
                return (false, forwardIndex);
            }

            try
            {
                var mainRect = mainWindow.Properties.BoundingRectangle.Value;

                // 查找所有符合条件的子控件
                AutomationElement[] items = mainWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.Image));
                List<AutomationElement> target = new List<AutomationElement>();

                foreach (var item in items.Reverse()) // 遍历反转后的集合，避免额外的内存分配
                {
                    var boundingRect = item.Properties.BoundingRectangle.Value;

                    if (boundingRect.IsEmpty || mainRect.IsEmpty)
                    {
                        LogManager.Error($"[SelectMsgItem] 分类:{msgType} 无法获取控件的边界信息！");
                        continue;
                    }

                    // 筛选符合条件的控件
                    if (boundingRect.Height == 1 && boundingRect.Width < mainRect.Width / 2)
                    {
                        var parentElement = item.Parent;
                        if (parentElement != null)
                        {
                            target.Add(parentElement);
                        }
                    }
                }

                int total = target.Count;
                if (total == 0)
                {
                    LogManager.Error($"[SelectMsgItem] 分类:{msgType} 没有任何资源");
                    return (false, forwardIndex);
                }

                // 生成有效索引池
                var validIndexes = target.Select((elem, index) => new { elem, index })
                                       .Where(x => IsElementValid(x.elem))
                                       .Select(x => x.index)
                                       .ToList();

                while (validIndexes.Count > 0)
                {
                    // 动态随机选择并移除
                    int randomPos = ThreadSafeRandom.Next(0, validIndexes.Count);
                    int currentIndex = validIndexes[randomPos];
                    // 移除已选择的索引
                    validIndexes.RemoveAt(randomPos);

                    AutomationElement targetElement = target[currentIndex];

                    // 判断控件是否超过窗口高度
                    var targetRect = targetElement.Properties.BoundingRectangle.Value;
                    if (targetRect.Y + 100 > mainRect.Height)
                    {
                        int newX = (int)(Screen.PrimaryScreen.Bounds.Width * 0.2);
                        int newW = mainRect.Width;
                        int newH = targetRect.Y + 200;
                        // 判断新窗口是否超出屏幕高度
                        if (newH - 200 > Screen.PrimaryScreen.Bounds.Height)
                        {
                            LogManager.Error($"[SelectMsgItem] 元素超过屏幕高度, 切换下一个目标");
                            continue;
                        }

                        LogManager.Info($"[SelectMsgItem] 调整父窗口:x:{newX}, y:50, width:{newW}, height:{newH}");
                        Win32Api.SetWindowPos(mainWindow.Properties.NativeWindowHandle,
                            IntPtr.Zero,
                            newX,
                            50,
                            newW,
                            newH,
                            Win32Api.SWP_NOMOVE);

                        await Task.Delay(500); // 等待窗口调整完成
                    }

                    try
                    {
                        await Task.Delay(1000);
                        // 执行点击操作
                        targetElement.Click();
                        await Task.Delay(1000);
                        return (true, currentIndex);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[SelectMsgItem] 点击失败:{currentIndex}", ex);
                    }
                }

                return (false, -1);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[SelectMsgItem] 发生未知错误: {ex.Message}", ex);
                return (false, forwardIndex);
            }
        }

        public async Task<(bool selectResult, int forwardIndex)> SelectMsgItem(AutomationElement mainWindow, string msgType)
        {
            int forwardIndex = 0;
            if (mainWindow == null)
            {
                LogManager.Error("[SelectMsgItem] mainWindow 为空！");
                return (false, forwardIndex);
            }

            try
            {
                var mainRect = mainWindow.Properties.BoundingRectangle.Value;

                // 查找所有符合条件的子控件
                var items = mainWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.Image));
                var target = new List<AutomationElement>();

                foreach (var item in items.Reverse()) // 遍历反转后的集合，避免额外的内存分配
                {
                    var boundingRect = item.Properties.BoundingRectangle.Value;

                    if (boundingRect.IsEmpty || mainRect.IsEmpty)
                    {
                        LogManager.Error($"[SelectMsgItem] 分类:{msgType} 无法获取控件的边界信息！");
                        continue;
                    }

                    // 筛选符合条件的控件
                    if (boundingRect.Height == 1 && boundingRect.Width < mainRect.Width / 2)
                    {
                        var parentElement = item.Parent;
                        if (parentElement != null)
                        {
                            target.Add(parentElement);
                        }
                    }
                }

                if (target.Count == 0)
                {
                    LogManager.Error($"[SelectMsgItem] 分类:{msgType} 没有任何资源");
                    return (false, forwardIndex);
                }

                // 生成有效索引池
                var validIndexes = target.Select((elem, index) => new { elem, index })
                                         .Where(x => IsElementValid(x.elem))
                                         .Select(x => x.index)
                                         .ToList();

                while (validIndexes.Count > 0)
                {
                    // 动态随机选择并移除
                    int randomPos = ThreadSafeRandom.Next(0, validIndexes.Count);
                    int currentIndex = validIndexes[randomPos];
                    validIndexes.RemoveAt(randomPos);

                    var targetElement = target[currentIndex];
                    var targetRect = targetElement.Properties.BoundingRectangle.Value;

                    if (targetRect.Y + 100 > mainRect.Height)
                    {
                        if (!AdjustWindowPosition(mainWindow, targetElement))
                        {
                            continue;
                        }

                        await Task.Delay(1000);// 等待窗口调整完成
                    }

                    try
                    {
                        // 执行点击操作
                        targetElement.Click();
                        return (true, currentIndex);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Error($"[SelectMsgItem] 点击失败:{currentIndex}", ex);
                    }
                }

                return (false, -1);
            }
            catch (Exception ex)
            {
                LogManager.Error($"[SelectMsgItem] 发生未知错误: {ex.Message}", ex);
                return (false, forwardIndex);
            }
        }


        // 判断元素有效性方法
        bool IsElementValid(AutomationElement element)
        {
            return element != null && element.Properties.IsEnabled;
        }

        // 调整窗口位置方法
        bool AdjustWindowPosition(AutomationElement mainWindow, AutomationElement targetElement)
        {
            var targetRect = targetElement.Properties.BoundingRectangle.Value;
            var mainRect = mainWindow.Properties.BoundingRectangle.Value;
            int newX = (int)(Screen.PrimaryScreen.Bounds.Width * 0.2);
            int newW = mainRect.Width;
            int newH = targetRect.Y + 200;

            if (newH - 200 > Screen.PrimaryScreen.Bounds.Height)
            {
                LogManager.Error($"[AdjustWindowPosition] 元素超过屏幕高度, 切换下一个目标");
                return false;
            }

            LogManager.Info($"[AdjustWindowPosition] 调整父窗口:x:{newX}, y:50, width:{newW}, height:{newH}");
            Win32Api.SetWindowPos(mainWindow.Properties.NativeWindowHandle,
                IntPtr.Zero,
                newX,
                50,
                newW,
                newH,
                Win32Api.SWP_NOMOVE);

            return true;
        }
    }
}
